打包优化:CSS 打包优化
概述
在之前的打包优化中只关注了 JS 文件,但查看构建日志后发现 CSS 文件体积竟达 300+ KB,超过 JS 文件。原因是 Element Plus 的样式被完整打包进了 index.css。本节解决生产环境下 CSS 的外部化问题。
问题分析
构建产物对比
dist/assets/index-3f2a1b.css 320.45 kB │ gzip: 45.12 kB ← CSS 过大
dist/assets/index-a1b2c3.js 231.68 kB │ gzip: 78.32 kB ← JS 正常
text
查看打包后的 CSS
打开 dist/assets/index.css,发现全部是 Element Plus 的样式。原因在于 main.ts 中导入了 Element Plus 的 CSS:
// main.ts
import 'element-plus/dist/index.css' // 第 7 行:完整样式
import 'element-plus/theme-chalk/dark/css-vars.css' // 第 19 行:暗黑模式变量
typescript
而 vite-plugin-cdn2 只处理了 JS 文件的外部化,并未处理 CSS。
解决方案
条件导入 CSS
// main.ts
// 开发模式:本地导入 Element Plus 样式
// 生产模式:由 CDN 加载样式
if (import.meta.env.DEV) {
// 使用动态 import,仅在开发环境加载
import('element-plus/dist/index.css')
import('element-plus/theme-chalk/dark/css-vars.css')
}
typescript
注意:不能在顶层使用
if+ 静态import,ES 模块规范要求 import 必须在顶层。需要使用动态import()实现条件加载。
CDN 中配置 CSS
// vite.config.ts
cdn({
modules: [
{
name: 'element-plus',
var: 'ElementPlus',
path: 'https://unpkg.com/element-plus/dist/index.full.min.js',
// CSS 也通过 CDN 加载
css: 'https://unpkg.com/element-plus/dist/index.css'
}
]
})
typescript
效果对比
| 指标 | 优化前 | 优化后 |
|---|---|---|
| index.css | 320 KB | ~30 KB(仅项目样式) |
| Element Plus CSS | 打包在 index.css 中 | CDN 加载 |
| 暗黑模式 CSS | 打包在 index.css 中 | CDN 加载 |
| 总体积 | ~550 KB | ~260 KB |
import.meta.env 模式判断
| 环境变量 | 开发模式 | 生产模式 |
|---|---|---|
import.meta.env.DEV | true | false |
import.meta.env.PROD | false | true |
import.meta.env.MODE | 'development' | 'production' |
// 三种判断方式等价
if (import.meta.env.DEV) { /* 仅开发模式 */ }
if (!import.meta.env.PROD) { /* 仅开发模式 */ }
if (import.meta.env.MODE !== 'production') { /* 仅开发模式 */ }
typescript
静态 import vs 动态 import
// 错误:不能在 if 中使用静态 import
if (import.meta.env.DEV) {
import 'element-plus/dist/index.css' // SyntaxError
}
// 正确:使用动态 import
if (import.meta.env.DEV) {
import('element-plus/dist/index.css') // 返回 Promise
}
// 正确:使用 Vite 的 ?inline 导入
// 但这只是内联,不是条件导入
typescript
实践要点
- 打包优化不能只关注 JS,CSS 体积同样需要检查
vite-plugin-cdn2的css配置可以处理组件库 CSS 的 CDN 化main.ts中条件导入 CSS 使用动态import(),不能用静态import- 通过
import.meta.env.DEV判断当前环境,仅开发模式本地加载样式 - 优化后 CSS 体积从 320KB 降至 ~30KB,Element Plus 样式通过 CDN 加载
↑